package org.codehaus.activemq.message.util;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

class FileDataBlock
{
  private RandomAccessFile dataBlock;
  private File file;
  private long maxSize;
  private long currentOffset;

  FileDataBlock(File file, long maxSize)
    throws IOException
  {
    this.file = file;
    this.maxSize = maxSize;
    this.dataBlock = new RandomAccessFile(file, "rw");
    if (this.dataBlock.length() > 0L) {
      this.currentOffset = this.dataBlock.readLong();
    }
    else {
      this.dataBlock.writeLong(0L);
      this.currentOffset = this.dataBlock.length();
    }
  }

  synchronized void close()
    throws IOException
  {
    this.dataBlock.close();
    this.file.delete();
  }

  synchronized boolean isEnoughSpace(byte[] data)
    throws IOException
  {
    return this.dataBlock.length() + data.length < this.maxSize;
  }

  synchronized void write(byte[] data)
    throws IOException
  {
    this.dataBlock.seek(this.dataBlock.length());
    this.dataBlock.writeInt(data.length);
    this.dataBlock.write(data);
  }

  synchronized byte[] read()
    throws IOException
  {
    byte[] result = null;
    if ((this.currentOffset > 0L) && (this.currentOffset < this.dataBlock.length())) {
      this.dataBlock.seek(this.currentOffset);
      int length = this.dataBlock.readInt();
      result = new byte[length];
      this.dataBlock.readFully(result);
      this.currentOffset = this.dataBlock.getFilePointer();
      updateHeader(this.currentOffset);
    }
    return result;
  }

  private void updateHeader(long pos) throws IOException {
    this.dataBlock.seek(0L);
    this.dataBlock.writeLong(pos);
  }
}